package com.token.sysflow.service;

import com.alibaba.fastjson.JSONObject;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * java执行javaScript代码的工具类
 *
 */
public class JavaScriptUtil {
    /** 单例的JavaScript解析引擎 */
    private static final ScriptEngine javaScriptEngine;
    static {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scriptEngine = manager.getEngineByName("js");
        if (scriptEngine == null) {
            throw new RuntimeException("获取JavaScript解析引擎失败");
        }
        javaScriptEngine = scriptEngine;
    }
    /**
     * 执行一段JavaScript代码
     *
     * @param script JavaScript的代码
     * @return JavaScript代码运行结果的值
     * @throws ScriptException JavaScript代码运行异常
     */
    public static Object execute(String script) throws ScriptException {
        System.out.println("script = " + script);
        return javaScriptEngine.eval(script);
    }

    /**
     *
     * @param func
     * @param fieldValue
     * @return
     */
    public static String replaceStr(String func, JSONObject fieldValue){
        Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
        Matcher m = p.matcher(func);
        StringBuffer sb = new StringBuffer(100);
        while (m.find()) {
            String group = m.group(2);
            //规则中${值}中的值一样
//            System.out.println("符合规则中第二个的值"+group);

            //下一步是替换并且把替换好的值放到sb中
            Object tmp = fieldValue.get(group);
            if(tmp != null) {
//                System.out.println("tmp = " + tmp);
                m.appendReplacement(sb, getTypeValue(tmp));
//                System.out.println("sb = " + sb);
            }
        }
        //把符合的数据追加到sb尾
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     *
     * @param param 参数
     * @return
     */
    private static String getTypeValue(Object param){
        String str;
        if (param instanceof Integer) {
            str = String.valueOf(param);
        } else if (param instanceof String) {
            str = "'" + param + "'";
        } else if (param instanceof Double) {
            str = String.valueOf(param);
        } else if (param instanceof Float) {
            str = String.valueOf(param);
        } else if (param instanceof Long) {
            str = String.valueOf(param);
        } else if (param instanceof Boolean) {
            boolean b = (Boolean) param;
            str = String.valueOf(param);
        }else{
            str = "'" + param + "'";
        }
        return str;
    }
}